package com.summer.framework.common.util;


import java.math.BigInteger;
import java.util.UUID;

/**
 * ${DESCRIPTION}
 *
 * @author 文锐
 * @email wenrui@muyuanfoods.com
 * @date 2018/01/14
 */
public class UUIDUtil {

    /**
     * Create uuid
     *
     * @return url62 encoded id
     */
    public static String create() {
        return encode(UUID.randomUUID());
    }

    /**
     * Encode UUID to url62 id
     *
     * @param uuid UUID to be encoded
     * @return url62 encoded uuid
     */
    public static String encode(UUID uuid) {
        BigInteger pair = ElegantPairing.pair(
                BigInteger.valueOf(uuid.getMostSignificantBits()),
                BigInteger.valueOf(uuid.getLeastSignificantBits())
        );
        return Base62.encode(pair);
    }

    /**
     * Decode url62 id to UUID
     *
     * @param id url62 encoded id
     * @return decoded UUID
     */
    public static UUID decode(String id) {
        BigInteger decoded = Base62.decode(id);
        BigInteger[] unpaired = ElegantPairing.unpair(decoded);
        return new UUID(unpaired[0].longValue(), unpaired[1].longValue());
    }

    public static void main(String[] args) {
/*        UUID uuid = UUID.randomUUID();
        System.out.println(uuid);
        String encodeUUID = encode(uuid);
        System.out.println(encodeUUID);
        UUID decodeUUID = decode(encodeUUID);
        System.out.println(decodeUUID);*/
        for (int i = 0; i < 100; i++) {
            System.out.println(create());
        }
    }
}
